<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户日志</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <!-- 员工姓名 -->
            <el-form-item label="姓名工号">
              <el-autocomplete
                v-model="formInline.userId"
                :fetch-suggestions="querySearchAsync"
                placeholder="请输入姓名"
                @select="handleSelect"
                clearable
              >
                <template slot-scope="{ item }">
                  <div class="selName">
                    <span>{{ item.userName }}</span>
                    <span>[{{ item.userId }}]</span>
                  </div>
                </template>
              </el-autocomplete>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="menusData"
          border
          @selection-change="selsChange"
          style="width: 100%"
          height="395"
          ref="menusData"
        >
          <!-- IP -->
          <el-table-column
            prop="ip"
            label="IP"
            width="150"
          ></el-table-column>
           <!-- 操作人 -->
          <el-table-column
            prop="createUserId"
            label="操作人"
            width="150"
          ></el-table-column>
          <!-- 操作时间 -->
          <el-table-column label="操作时间" width="200">
            <template slot-scope="scope">{{ scope.row.createTime | filterTime }}</template>
          </el-table-column>
          <!-- 类别 -->
          <el-table-column
            label="类别"
            width="80"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.type === 'info'">正常</span>
              <span v-else>异常</span>
            </template>
          </el-table-column>
          <!-- 日志 -->
          <el-table-column
            :show-overflow-tooltip="true"
            prop="log"
            label="日志"
          ></el-table-column>
        </el-table>
         <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';

export default {
  name: 'userlog',
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 过滤器
  filters: {
    // 时间显示过滤
    filterTime (value) {
      return moment(value).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(value).format('YYYY-MM-DD HH:mm:ss');
    }
  },

  // 当前页面数据
  data () {
    return {
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取所有用户
      usersAll: [],

      // 检索匹配
      restaurants: [],
      state: '',
      timeout: null,

      // 搜索条件
      formInline: {
        userId: ''
      },

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20
    };
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有员工
    this.getUsersAll();

    // 加载数据
    this.getmenusDataByPage();
  },
  mounted () {
    this.restaurants = this.loadAll();
  },
  methods: {
    // 获取所有员工数据
    getUsersAll () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          for (let i = datas.length; i--;) {
            _this.usersAll.push({
              compName: datas[i].compName,
              deptName: datas[i].deptName,
              userId: datas[i].userId,
              userName: datas[i].userName
            });
          };
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 加载全部员工数据
    loadAll () {
      return this.usersAll;
    },

    // 自动检索匹配
    querySearchAsync (queryString, cb) {
      let _this = this;
      let restaurants = _this.restaurants;
      let results = queryString ? restaurants.filter(_this.createStateFilter(queryString)) : restaurants;
      clearTimeout(_this.timeout);
      _this.timeout = setTimeout(() => {
        cb(results);
      }, 300 * Math.random());
    },

    // 查询
    createStateFilter (queryString) {
      return (state) => {
        return (state.userName.indexOf(queryString) === 0);
      };
    },

    // 选中赋值
    handleSelect (item) {
      this.formInline.userId = item.userId;
    },

    // 按钮级授权
    authorization (data) {
      let _this = this;
      for (let i in data) {
        if (data['sel'] === 0) {
          _this.btnSel = false;
        }
        if (data['add'] === 0) {
          _this.btnAdd = false;
        }
        if (data['del'] === 0) {
          _this.btnDel = false;
        }
        if (data['upload'] === 0) {
          _this.btnUpload = false;
        }
        if (data['down'] === 0) {
          _this.btnDown = false;
        }
        if (data['edit'] === 0) {
          _this.btnEdit = false;
        }
        return i;
      }
    },

    // 查询
    selHandle: function () {
      let _this = this;
      // 收集请求数据
      let params = {
        userId: _this.formInline.userId === null ? '' : _this.formInline.userId,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 根据项目ID获取分页数据
      _this.$http.raw('api/findSysLogs', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          _this.total = datas.total;
          // 数据结果集
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新页面数据
    getmenusDataByPage () {
      let _this = this;
      // 收集请求信息
      let params = {
        userId: _this.formInline.userId === null ? '' : _this.formInline.userId,
        pageNum: _this.currentPage,
        pageSize: _this.pageSize
      };
      // 获取分页数据
      _this.$http.raw('api/findSysLogs', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          _this.total = datas.total;
          _this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
